
_array_t = {
    "uint8":Uint8Array,
    "int32":Int32Array,
    "uint32":Uint32Array,
  }

buf2str = (buf) ->
  v = new Uint8Array(buf)
  return String.fromCharCode.apply(null,(v[i] for i in [0...v.length]))

class ClientConnection
  constructor: () ->
    This = this
    $.get("../data/bit_protocol", (data) -> This.loadProto(data))
    @ws = new WebSocket("ws://localhost:14285")
    @ws.onclose = (e) ->
      console.log("Lost connection.")
    @ws.onopen = (e) ->
      console.log("Gained connection.")
      This.init()
    @ws.onmessage = (e) ->
      This.handleMessage(e)
  loadProto: (data) ->
    @proto = JSON.parse(data.substr(9)) # 9 = len("protocol=")
    @rlookup = {}
    for bit of @proto
      @rlookup[@proto[bit][0]] = bit
    @init()
  handleMessage: (data) ->
    console.log(data)
  init: () ->
    if (@proto is undefined or @ws.readyState isnt 1)
      return
    console.log("Initiating Connection")
    @send("PING",{"timestamp":43})
  send: (bit,data) ->
    bit = @proto[bit]
    total = 0
    for id,subbit of bit[1..]
      [name,size,t] = subbit
      total+=size
    buf = new ArrayBuffer(4+total)
    console.log(4+total)
    (new Uint32Array(buf,0,1))[0]=bit[0]
    total = 4
    for id,subbit of bit[1..]
      [name,size,t] = subbit
      console.log(_array_t[t])
      (new (_array_t[t])(buf,total,1))[0] = data[name]
      total+=size
    buf = buf2str(buf)
    console.log("Sending "+buf.length+" bytes")
    @ws.send(buf)

